/**
 * Created by SunLunatic on 2015/4/3.
 */
var common = require("../util/common");

exports.list = function(req, res){
    var resBody = {};
    common.getDb('article').find({}, {sort:{"ctime": -1}}, function(err, doc){
        resBody.articles = doc;
        res.render("article/list", common.baseData(req, resBody));
    });
}
exports.write = function(req, res){
    res.render("article/write", common.baseData(req, {"article": ""}));
}
exports.insert = function(req, res){
    var id = req.body.id;
    console.info(id);
    if(id != ""){
        id = Number(id);
        delete req.body.ctime;
        req.body.id = id;
        common.getDb("article").update({"id": id}, {$set: req.body});
    }else {
        req.body.vtime = 0;
        req.body.rtime = 0;
        common.insert("article", function (id) {
            req.body["id"] = id;
            common.getDb('article').insert(req.body);
        });
    }
    res.end();
}
exports.show = function(req, res){
    var id = Number(req.params.id);
    var resBody = {};
    common.getDb("article").findAndModify({"id" : id}, {$inc:{'vtime': 1}}, function(err, doc){
        console.info(doc);
        resBody.article = doc;
        res.render("article/show", common.baseData(req, resBody));
    });
}
exports.modify = function(req, res){
    var id = Number(req.params.id);
    var resBody = {};
    common.getDb("article").findOne({"id" : id}, function(err, doc){
        resBody.article = doc;
        res.render("article/write", common.baseData(req, resBody));
    })
}